package com.dayuanit.dy17.atm.atmbackoffice.controller;

import com.dayuanit.dy17.atm.atmbackoffice.dto.ResponseDTO;
import com.dayuanit.dy17.atm.atmbackoffice.entity.User;
import com.dayuanit.dy17.atm.atmbackoffice.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @RequestMapping(value = "/user/addUser", method = RequestMethod.POST)
    public ResponseDTO addUser(String username, String password) {
        userService.createUser(username, password);
        return ResponseDTO.success();
    }

    @RequestMapping("/user/loadMenu")
    public ResponseDTO loadMenu() {
        return ResponseDTO.success(userService.listUserMenu3(getUserId()));
    }

    @RequestMapping("/user/login")
    public ResponseDTO login(String username, String password, HttpSession httpSession) {
        logger.info("登录信息 username={}, password={}", username, password);
        Subject subject = SecurityUtils.getSubject();
        subject.login(new UsernamePasswordToken(username, password.toCharArray()));

        //此session不是HttpSession 又由于我们认证的信息在shiro中，所以无法从HttpSession取到用户的信息
        Session session = subject.getSession();
        logger.info(">>>>>>" + session.toString());

        User user = (User)subject.getPrincipal();
        logger.debug(">>>>>{}", user.getUsername());

        httpSession.setAttribute("username", user.getUsername());
        return ResponseDTO.success();
    }

    @RequestMapping("/user/logout")
    public ResponseDTO logout(HttpSession httpSession) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();//清理掉shiro里的认证信息

        return ResponseDTO.success();
    }

}
